package com.nbjtjc.safe.service.report;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import cn.afterturn.easypoi.util.PoiMergeCellUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.nbjtjc.safe.bean.EduDailyExamineScoreBean;
import com.nbjtjc.safe.bean.Result;
import com.nbjtjc.safe.mapper.edu.*;
import com.nbjtjc.safe.mapper.sys.SysUserMapper;
import com.nbjtjc.safe.mapper.sys.SysUserReportMapper;
import com.nbjtjc.safe.model.edu.*;
import com.nbjtjc.safe.model.sys.SysUserReport;
import com.nbjtjc.safe.util.FileUtil;
import com.nbjtjc.safe.util.MyShiroUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 教育培训的台账导出
 *
 * @auther guqianbin
 * @date 2018/5/8 10:20
 **/
@Service
public class EduReportService {
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private EduRequirementInvestigationMapper eduRequirementInvestigationMapper;
    //TODO 临时文件的清理
    @Value("${file.path.tempPath}")
    private String fileTempPath;
    @Autowired
    private FileUtil fileUtil;

    @Autowired
    private EduPlanListMapper eduPlanListMapper;

    @Autowired
    private EduCertificateMapper eduCertificateMapper;
    @Autowired
    EduCertificateRetrainMapper eduCertificateRetrainMapper;

    @Autowired
    private EduEntryTrainingMapper eduEntryTrainingMapper;
    @Autowired
    private EduReassignmentMapper eduReassignmentMapper;

    @Autowired
    private EduDailyInfoMapper eduDailyInfoMapper;

    @Autowired
    private EduDailyRecordMapper eduDailyRecordMapper;

    @Autowired
    private EduDailyExamineListMapper eduDailyExamineListMapper;

    @Autowired
    private EduDailyExamineScoreMapper eduDailyExamineScoreMapper;
    @Autowired
    SysUserReportMapper sysUserReportMapper;

    
    /**
     * 找出所有教育培训台账列表
     *
     */
    public Result findYear() {
    	Result result = new Result();
    	Set resultSet = new HashSet();
    	List<String> years = new ArrayList();

    	int currentComId=MyShiroUtils.getCompanyId();
    	//需求调查
    	years = eduRequirementInvestigationMapper.findYear(currentComId);
    	resultSet.addAll(years);
    	//培训计划
    	years = eduPlanListMapper.findYear(currentComId);
    	resultSet.addAll(years);

    	//持证培训
    	years = eduCertificateMapper.findYear(currentComId);
    	resultSet.addAll(years);
    	years = eduCertificateRetrainMapper.findYear(currentComId);
    	resultSet.addAll(years);
    	
    	//三级培训
    	years = sysUserMapper.findYear(currentComId);
    	resultSet.addAll(years);
    	//转岗培训    	
    	years = eduReassignmentMapper.findYear(currentComId);
    	resultSet.addAll(years);
    	//日常培训
    	years = eduDailyInfoMapper.findYear(currentComId);
    	resultSet.addAll(years);
    	
    	result.setData(resultSet);
    	return result;
    }
    
    public Result eduList(HttpServletResponse response, Date year) {
    	Result result = new Result();
       	Calendar   calendar   =   new   GregorianCalendar(); 
   
        //一年的时间范围
    	calendar.setTime(year);
    	calendar.add(calendar.YEAR, 1);
    	Map resultMap = new HashMap();
    	List<String> titles=new ArrayList();

    	
    	Date currentDate = new Date();
        //从业人员花名册
    	SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
    	sdf.format(year);
    	List<SysUserReport> sysUserReports = sysUserReportMapper.searchByYear(sdf.format(year));
    	if(CollectionUtil.isNotEmpty(sysUserReports)){
    		titles.add("从业人员花名册");
    		resultMap.put("sysUserReports", sysUserReports);
    	}
//        if(year.getTime() <= currentDate.getTime()){
//            titles.add("从业人员花名册");
//        }
//    	resultMap.put("从业人员花名册","");
    	//需求调查,一年一次，改为一年可有多次
    	//根据年份找出需求调查主表ID
    	Integer eduRequirementInvestigationId=-1;
    	EduRequirementInvestigation eduRequirementInvestigationSample = new EduRequirementInvestigation();
    	eduRequirementInvestigationSample.setCreateYear(year);
    	eduRequirementInvestigationSample.setCompanyId(MyShiroUtils.getCompanyId());

    	List<EduRequirementInvestigation> eduRequirementInvestigations = eduRequirementInvestigationMapper.search(eduRequirementInvestigationSample);
    	if(CollectionUtil.isEmpty(eduRequirementInvestigations)){

    		resultMap.put("eduRequirementInvestigation", null);
//    	}else if(eduRequirementInvestigations.size()>1){  //一年一次该代码有效，一年多次则需注释
//    		result.setFalse("该年份需求调查有多个，请检查");
//    		return result;
    	}else{
//    		resultMap.put("eduRequirementInvestigation", eduRequirementInvestigations.get(0));

    		resultMap.put("eduRequirementInvestigation", eduRequirementInvestigations);
        	titles.add("安全培训教育需求调查表");       	
    	}
    	//培训计划,一年一次
    	Integer eduPlanId=-1; 
        	//根据年份找出培训计划主表ID
    		EduPlanList eduPlanListSample = new EduPlanList();
    		eduPlanListSample.setCreateYear(year);
    		eduPlanListSample.setCompanyId(MyShiroUtils.getCompanyId());

        	List<EduPlanList> eduPlanLists1 = eduPlanListMapper.search(eduPlanListSample);
        	if(CollectionUtil.isEmpty(eduPlanLists1)){
//        		result.setFalse("该年份需求调查记录为空");
//        		return result;
        		resultMap.put("eduPlanList", null);
        	}else if(eduPlanLists1.size()>1){
        		result.setFalse("该年份员工获赔记录有多个，请检查");
        		return result;
        	}else{
//        		eduPlanId = eduPlanLists1.get(0).getId();
        		resultMap.put("eduPlanList", eduPlanLists1.get(0));
            	titles.add("安全培训教育计划表");

        	}
    	//持证培训,一年多次
    	List<Integer> certIds=new ArrayList();
    	EduCertificate eduCertificateSample = new EduCertificate();
    	List<EduCertificate> eduCertificates = new ArrayList();
    	eduCertificateSample.setStartDate(year);
    	eduCertificateSample.setEndDate(calendar.getTime());
    	eduCertificateSample.setCompanyId(MyShiroUtils.getCompanyId());

       eduCertificates = eduCertificateMapper.searchDetail(eduCertificateSample);
       if(CollectionUtil.isEmpty(eduCertificates)){
    	   resultMap.put("eduCertificates",null);
       }else{
//    	   for(EduCertificate cert:eduCertificates){
//    		   certIds.add(cert.getId());
//    	   }
    	   resultMap.put("eduCertificates", eduCertificates);
       	titles.add("安全生产相关负责人及安全生产管理人员安全培训教育登记表");


       }
    	
    	
    	//三级培训,一年多次
    	List<Integer> entryIds=new ArrayList();
    	
    	EduEntryTraining eduEntryTrainingSample = new EduEntryTraining();
    	List<EduEntryTraining> eduEntryTrainings = new ArrayList();
    	eduEntryTrainingSample.setStartDate(year);
    	eduEntryTrainingSample.setEndDate(calendar.getTime());
    	eduEntryTrainingSample.setCompanyId(MyShiroUtils.getCompanyId());

    	eduEntryTrainings = eduEntryTrainingMapper.searchDetail(eduEntryTrainingSample);
       if(CollectionUtil.isEmpty(eduEntryTrainings)){
    	   resultMap.put("eduEntryTrainings",null);
       }else{
//    	   for(EduEntryTraining entry:eduEntryTrainings){
//    		   entryIds.add(entry.getId());
//    	   }
    	   resultMap.put("eduEntryTrainings", eduEntryTrainings);
           titles.add("新入职人员安全培训教育登记表");


       }

    	//转岗培训,一年多次
    	List<Integer> reasIds=new ArrayList();
    	
    	EduReassignment eduReassignmentSample = new EduReassignment();
    	List<EduReassignment> eduReassignments = new ArrayList();
    	eduReassignmentSample.setStartDate(year);
    	eduReassignmentSample.setEndDate(calendar.getTime());
    	eduReassignmentSample.setCompanyId(MyShiroUtils.getCompanyId());

    	eduReassignments = eduReassignmentMapper.searchDetail(eduReassignmentSample);
       if(CollectionUtil.isEmpty(eduReassignments)){
    	   resultMap.put("eduReassignments",null);
       }else{
//    	   for(EduReassignment reas:eduReassignments){
//    		   reasIds.add(reas.getId());
//    	   }
    	   resultMap.put("eduReassignments", eduReassignments);
         	titles.add("转岗、调岗、脱岗人员安全培训教育登记表");


       }

    	//日常培训,一年多次
    	List<Integer> dailyIds=new ArrayList();

    	EduDailyInfo eduDailyInfoSample = new EduDailyInfo();
    	List<EduDailyInfo> eduDailyInfos = new ArrayList();
    	eduDailyInfoSample.setStartDate(year);
    	eduDailyInfoSample.setEndDate(calendar.getTime());
    	eduDailyInfoSample.setCompanyId(MyShiroUtils.getCompanyId());

    	eduDailyInfos = eduDailyInfoMapper.search(eduDailyInfoSample);
       if(CollectionUtil.isEmpty(eduDailyInfos)){
    	   resultMap.put("eduDailyInfos",null);
       }else{
//    	   for(EduDailyInfo daily:eduDailyInfos){
//    		   dailyIds.add(daily.getId());
//    	   }
    	   resultMap.put("eduDailyInfos", eduDailyInfos);
        	titles.add("从业人员日常安全培训教育登记表");


       }
       resultMap.put("titles", titles);


    	result.setData(resultMap);
    	return result;
    }

//    /**
//     * 导出从业人员的花名册
//     *
//     * @param response
//     * @param sysUser
//     */
//    public void eduUserListExcel(HttpServletResponse response, SysUser sysUser) {
//        try {
//            List<SysUser> sysUsers = sysUserMapper.search(sysUser, new Page());
//            Map<String, Object> map = new HashMap<String, Object>();
//            if (CollectionUtil.isEmpty(sysUsers)) {
//                map.put("users", new ArrayList<>());
//            } else {
//                for (int i = 0; i < sysUsers.size(); i++) {
//                    sysUsers.get(i).setNum(i + 1);
//                }
//                map.put("users", sysUsers);
//            }
//            TemplateExportParams params = new TemplateExportParams(
//                    "reportTemplates/edu/eduListOfPerson.xlsx");
//            params.setHeadingStartRow(0);
//            params.setHeadingRows(5);
//
//            Workbook workbook = ExcelExportUtil.exportExcel(params, map);
//
//            PoiMergeCellUtil.mergeCells(workbook.getSheetAt(0), 5, 0, 7);
//            File savefile = new File(fileTempPath);
//            if (!savefile.exists()) {
//                savefile.mkdirs();
//            }
//            String filePath = fileTempPath + "从业人员花名册-" + "-" + MyShiroUtils.getSessionUserId() + ".xlsx";
////            String filePath = fileTempPath + "从业人员花名册-" + "-" + ".xlsx";
//            FileOutputStream fos = new FileOutputStream(filePath);
//            workbook.write(fos);
//            fos.close();
//            fileUtil.writeFile(response, new File(filePath));
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }
//
//    /**
//     * 安全培训教育需求调查表
//     *
//     * @param response
//     * @param eduRequirementInvestigationId
//     */
//    //TODO excel表格导出有问题
//    public void eduRequirementInvestExcel(HttpServletResponse response
//            , int eduRequirementInvestigationId) {
//        try {
//            Map<String, Object> map = new HashMap<>();
//            EduRequirementInvestigation eduRequirementInvestigation = new EduRequirementInvestigation();
//            eduRequirementInvestigation.setId(eduRequirementInvestigationId);
//            List<EduRequirementInvestigation> eduRequirements =
//                    eduRequirementInvestigationMapper.search(eduRequirementInvestigation);
//            if (CollectionUtil.isNotEmpty(eduRequirements)) {
//                map.put("require", eduRequirements.get(0));
//                if (CollectionUtil.isNotEmpty(eduRequirements.get(0).getEduRequirementSurveyItems())) {
//                    map.put("its", eduRequirements.get(0).getEduRequirementSurveyItems());
//                }
//            } else {
//                map.put("require", new EduRequirementInvestigation());
//                map.put("its", new ArrayList<>());
//            }
//            TemplateExportParams params = new TemplateExportParams(
//                    "reportTemplates/edu/eduRequireInvest.xlsx");
//            params.setHeadingStartRow(0);
//            params.setHeadingRows(3);
//
//            Workbook workbook = ExcelExportUtil.exportExcel(params, map);
//
//            PoiMergeCellUtil.mergeCells(workbook.getSheetAt(0), 3, 0, 9);
//            File savefile = new File(fileTempPath);
//            if (!savefile.exists()) {
//                savefile.mkdirs();
//            }
//            String filePath = fileTempPath + "安全培训教育需求调查表-" + "-" + MyShiroUtils.getSessionUserId() + ".xlsx";
//            FileOutputStream fos = new FileOutputStream(filePath);
//            workbook.write(fos);
//            fos.close();
//            fileUtil.writeFile(response, new File(filePath));
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }
//
//
//    /**
//     * 安全培训教育计划表
//     *
//     * @param response
//     * @param eduPlanId
//     */
//    public void eduPlanExcel(HttpServletResponse response, int eduPlanId, int year) {
//        try {
//            Map<String, Object> map = new HashMap<>();
//            EduPlanList eduPlanList = new EduPlanList();
//            eduPlanList.setId(eduPlanId);
//            eduPlanList.setCreateYear(DateUtil.parse(year + "0101"));
//            List<EduPlanList> eduPlanLists = eduPlanListMapper.search(eduPlanList);
//            if (CollectionUtil.isEmpty(eduPlanLists)) {
//                return;
//            }
//            map.put("plan", eduPlanLists.get(0));
//            if (CollectionUtil.isEmpty(eduPlanLists.get(0).getEduPlanItems())) {
//                map.put("items", new ArrayList<>());
//            } else {
//                List<EduPlanItem> eduPlanItems = eduPlanLists.get(0).getEduPlanItems();
//                for (int i = 0; i < eduPlanItems.size(); i++) {
//                    eduPlanItems.get(i).setNum(i + 1);
//                }
//                map.put("items", eduPlanItems);
//            }
//            map.put("title", "（2017）培训教育活动计划表");
//            TemplateExportParams params = new TemplateExportParams(
//                    "reportTemplates/edu/eduSafePlan.xlsx");
//            params.setHeadingStartRow(0);
//            params.setHeadingRows(5);
//
//            Workbook workbook = ExcelExportUtil.exportExcel(params, map);
//
//            PoiMergeCellUtil.mergeCells(workbook.getSheetAt(0), 5, 0, 7);
//            File savefile = new File(fileTempPath);
//            if (!savefile.exists()) {
//                savefile.mkdirs();
//            }
//            String filePath = fileTempPath + "培训教育活动计划表-" + "-" + MyShiroUtils.getSessionUserId() + ".xlsx";
////            String filePath = fileTempPath + "从业人员花名册-" + "-" + ".xlsx";
//            FileOutputStream fos = new FileOutputStream(filePath);
//            workbook.write(fos);
//            fos.close();
//            fileUtil.writeFile(response, new File(filePath));
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }
//
//    /**
//     * 安全生产相关负责人及安全生产管理人员安全培训教育登记表
//     *
//     * @param response
//     */
//    public void eduCertificateExcel(HttpServletResponse response) {
//        try {
//            Map<String, Object> map = new HashMap<>();
//            List<EduCertificate> eduCertificates = eduCertificateMapper.search(new EduCertificate());
//            if (CollectionUtil.isEmpty(eduCertificates)) {
//                return;
//            }
//            map.put("eduCts", eduCertificates);
//            TemplateExportParams params = new TemplateExportParams(
//                    "reportTemplates/edu/eduCertificate.xlsx");
//            params.setHeadingStartRow(0);
//            params.setHeadingRows(3);
//
//            Workbook workbook = ExcelExportUtil.exportExcel(params, map);
//
//            PoiMergeCellUtil.mergeCells(workbook.getSheetAt(0), 3, 0, 12);
//            File savefile = new File(fileTempPath);
//            if (!savefile.exists()) {
//                savefile.mkdirs();
//            }
//            String filePath = fileTempPath + "安全生产相关负责人及安全生产管理人员安全培训教育登记表-" + "-" + MyShiroUtils.getSessionUserId() + ".xlsx";
//            FileOutputStream fos = new FileOutputStream(filePath);
//            workbook.write(fos);
//            fos.close();
//            fileUtil.writeFile(response, new File(filePath));
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }
//
//    /**
//     * 新入职人员安全培训教育登记表
//     *
//     * @param response
//     */
//    public void eduTrainExcel(HttpServletResponse response) {
//        try {
//            List<EduEntryTraining> eduEntryTrainings = eduEntryTrainingMapper.search(new EduEntryTraining());
//            if (CollectionUtil.isEmpty(eduEntryTrainings)) {
//                return;
//            }
//            for (int i = 0; i < eduEntryTrainings.size(); i++) {
//                eduEntryTrainings.get(i).setNum(i + 1);
//            }
//            Map<String, Object> map = new HashMap<>();
//            map.put("eduET", eduEntryTrainings);
//            TemplateExportParams params = new TemplateExportParams(
//                    "reportTemplates/edu/eduEntryTrain.xlsx");
//            params.setHeadingStartRow(0);
//            params.setHeadingRows(3);
//
//            Workbook workbook = ExcelExportUtil.exportExcel(params, map);
//
//            PoiMergeCellUtil.mergeCells(workbook.getSheetAt(0), 3, 0, 13);
//            File savefile = new File(fileTempPath);
//            if (!savefile.exists()) {
//                savefile.mkdirs();
//            }
//            String filePath = fileTempPath + "新入职人员安全培训教育登记表-" + "-" + MyShiroUtils.getSessionUserId() + ".xlsx";
//            FileOutputStream fos = new FileOutputStream(filePath);
//            workbook.write(fos);
//            fos.close();
//            fileUtil.writeFile(response, new File(filePath));
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }
//
//
//    /**
//     * 转岗、调岗、脱岗人员安全培训教育登记表
//     *
//     * @param response
//     */
//    public void eduReassignmentExcel(HttpServletResponse response) {
//        try {
//            List<EduReassignment> eduReassignments = eduReassignmentMapper.search(new EduReassignment());
//            if (CollectionUtil.isEmpty(eduReassignments)) {
//                return;
//            }
//            for (int i = 0; i < eduReassignments.size(); i++) {
//                eduReassignments.get(i).setNum(i + 1);
//            }
//            Map<String, Object> map = new HashMap<>();
//            map.put("eduR", eduReassignments);
//            TemplateExportParams params = new TemplateExportParams(
//                    "reportTemplates/edu/eduReassignment.xlsx");
//            params.setHeadingStartRow(0);
//            params.setHeadingRows(3);
//
//            Workbook workbook = ExcelExportUtil.exportExcel(params, map);
//
//            PoiMergeCellUtil.mergeCells(workbook.getSheetAt(0), 3, 0, 13);
//            File savefile = new File(fileTempPath);
//            if (!savefile.exists()) {
//                savefile.mkdirs();
//            }
//            String filePath = fileTempPath + "转岗、调岗、脱岗人员安全培训教育登记表-" + "-" + MyShiroUtils.getSessionUserId() + ".xlsx";
//            FileOutputStream fos = new FileOutputStream(filePath);
//            workbook.write(fos);
//            fos.close();
//            fileUtil.writeFile(response, new File(filePath));
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }
//
//    /**
//     * 从业人员日常安全培训教育登记表
//     *
//     * @param response
//     */
//    public void eduDailyInfoExcel(HttpServletResponse response, int year) {
//        try {
//            Date startDate = DateUtil.parse(year + "0101");
//            Date endDate = DateUtil.parse(year + "1231");
//            EduDailyInfo eduDailyInfo = new EduDailyInfo();
//            eduDailyInfo.setEndDate(endDate);
//            eduDailyInfo.setStartDate(startDate);
//            List<EduDailyInfo> eduDailyInfos = eduDailyInfoMapper.search(eduDailyInfo);
//            if (CollectionUtil.isEmpty(eduDailyInfos)) {
//                return;
//            }
//            for (int i = 0; i < eduDailyInfos.size(); i++) {
//                eduDailyInfos.get(i).setNum(i + 1);
//            }
//            Map<String, Object> map = new HashMap<>();
//            map.put("eduD", eduDailyInfos);
//            TemplateExportParams params = new TemplateExportParams(
//                    "reportTemplates/edu/eduDailyInfo.xlsx");
//            params.setHeadingStartRow(0);
//            params.setHeadingRows(3);
//
//            Workbook workbook = ExcelExportUtil.exportExcel(params, map);
//
//            PoiMergeCellUtil.mergeCells(workbook.getSheetAt(0), 3, 0, 13);
//            File savefile = new File(fileTempPath);
//            if (!savefile.exists()) {
//                savefile.mkdirs();
//            }
//            String filePath = fileTempPath + "从业人员日常安全培训教育登记表" + "-" + MyShiroUtils.getSessionUserId() + ".xlsx";
//            FileOutputStream fos = new FileOutputStream(filePath);
//            workbook.write(fos);
//            fos.close();
//            fileUtil.writeFile(response, new File(filePath));
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }
//
//    /**
//     * 教育培训活动记录excel导出
//     *
//     * @param response
//     * @param eduDailyRecordId
//     */
//    public void eduDailyRecordExcel(HttpServletResponse response, int eduDailyRecordId) {
//        try {
//            EduDailyRecord eduDailyRecord = eduDailyRecordMapper.selectByPrimaryKey(eduDailyRecordId);
//            if (ObjectUtil.isNull(eduDailyRecord)) {
//                return;
//            }
//            Map<String, Object> map = new HashMap<>();
//            map.put("edt", eduDailyRecord);
//            TemplateExportParams params = new TemplateExportParams(
//                    "reportTemplates/edu/eduDailyRecord.xlsx");
//            params.setHeadingStartRow(0);
//            params.setHeadingRows(3);
//
//            Workbook workbook = ExcelExportUtil.exportExcel(params, map);
//
//            PoiMergeCellUtil.mergeCells(workbook.getSheetAt(0), 3, 0, 13);
//            File savefile = new File(fileTempPath);
//            if (!savefile.exists()) {
//                savefile.mkdirs();
//            }
//            String filePath = fileTempPath + "教育培训活动记录" + "-" + MyShiroUtils.getSessionUserId() + ".xlsx";
//            FileOutputStream fos = new FileOutputStream(filePath);
//            workbook.write(fos);
//            fos.close();
//            fileUtil.writeFile(response, new File(filePath));
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }
//
//    public void eduDailyExamineListExcel(HttpServletResponse response, int eduDailyExamineListId) {
//        try {
//            EduDailyExamineList eduDailyExamineList =
//                    eduDailyExamineListMapper.selectByPrimaryKey(eduDailyExamineListId);
//            EduDailyExamineScore eduDailyExamineScore = new EduDailyExamineScore();
//            eduDailyExamineScore.setExamineId(eduDailyExamineListId);
//            List<EduDailyExamineScore> eduDailyExamineScores =
//                    eduDailyExamineScoreMapper.search(eduDailyExamineScore);
//            for (int i = 0; i < eduDailyExamineScores.size(); i++) {
//                eduDailyExamineScores.get(i).setNum(i + 1);
//            }
//            List<EduDailyExamineScoreBean> eduDailyExamineScoreBeans=new ArrayList<>();
//            for (int i = 0; i < eduDailyExamineScores.size(); i++) {
//                    if((i+1)<eduDailyExamineScores.size()){
//                        eduDailyExamineScoreBeans.add(new EduDailyExamineScoreBean(eduDailyExamineScores.get(i)
//                                ,eduDailyExamineScores.get(i+1)));
//                        i++;
//                    }else{
//                        eduDailyExamineScoreBeans.add(new EduDailyExamineScoreBean(eduDailyExamineScores.get(i)));
//                    }
//            }
//            Map<String, Object> map = new HashMap<>();
//            map.put("edel", eduDailyExamineList);
//            map.put("edes", eduDailyExamineScoreBeans);
//            TemplateExportParams params = new TemplateExportParams(
//                    "reportTemplates/edu/eduDailyExamine.xlsx");
//            params.setHeadingStartRow(0);
//            params.setHeadingRows(3);
//
//            Workbook workbook = ExcelExportUtil.exportExcel(params, map);
//
//            PoiMergeCellUtil.mergeCells(workbook.getSheetAt(0), 3, 0, 13);
//            File savefile = new File(fileTempPath);
//            if (!savefile.exists()) {
//                savefile.mkdirs();
//            }
//            String filePath = fileTempPath + "安全教育培训考核表" + "-" + MyShiroUtils.getSessionUserId() + ".xlsx";
//            FileOutputStream fos = new FileOutputStream(filePath);
//            workbook.write(fos);
//            fos.close();
//            fileUtil.writeFile(response, new File(filePath));
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }
    
    /**
     * 导出从业人员的花名册
     *
     * @param response
     * @param sysUser
     */
    public Result eduUserListExcel(HttpServletResponse response, String year) {
    	Result result = new Result();

        try {
            List<SysUserReport> sysUserReports = sysUserReportMapper.searchByYear(year);
            Map<String, Object> map = new HashMap<String, Object>();
            if (CollectionUtil.isEmpty(sysUserReports)) {
                map.put("users", new ArrayList<>());
            } else {
                for (int i = 0; i < sysUserReports.size(); i++) {
                	sysUserReports.get(i).setNum(i + 1);
                }
                map.put("users", sysUserReports);
            }
            TemplateExportParams params = new TemplateExportParams(
                    "reportTemplates/edu/eduListOfPerson.xlsx");
            params.setHeadingStartRow(0);
            params.setHeadingRows(5);

            Workbook workbook = ExcelExportUtil.exportExcel(params, map);

            PoiMergeCellUtil.mergeCells(workbook.getSheetAt(0), 5, 0, 7);
            File savefile = new File(fileTempPath);
            if (!savefile.exists()) {
                savefile.mkdirs();
            }
            String filePath = fileTempPath + "从业人员花名册-" + "-" + MyShiroUtils.getSessionUserId() + ".xlsx";
//            String filePath = fileTempPath + "从业人员花名册-" + "-" + ".xlsx";
            FileOutputStream fos = new FileOutputStream(filePath);
            workbook.write(fos);
            fos.close();
            fileUtil.writeFile(response, new File(filePath));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 安全培训教育需求调查表
     *done
     * @param response
     */
    //TODO excel表格导出有问题
    public Result eduRequirementInvestExcel(HttpServletResponse response, Date year) {//旧一年一个需求调查状况接口
    	Result result = new Result();
    	int eduRequirementInvestigationId=-1; 
        try {
        	
        	//根据年份找出需求调查主表ID
        	EduRequirementInvestigation eduRequirementInvestigationSample = new EduRequirementInvestigation();
        	eduRequirementInvestigationSample.setCreateYear(year);
        	eduRequirementInvestigationSample.setCompanyId(MyShiroUtils.getCompanyId());

        	List<EduRequirementInvestigation> eduRequirementInvestigations = eduRequirementInvestigationMapper.search(eduRequirementInvestigationSample);
        	if(CollectionUtil.isEmpty(eduRequirementInvestigations)){
//        		result.setFalse("该年份需求调查记录为空");
        		return result;
        	}else if(eduRequirementInvestigations.size()>1){
        		result.setFalse("该年份员工获赔记录有多个，请检查");
        		return result;
        	}else{
        		eduRequirementInvestigationId = eduRequirementInvestigations.get(0).getId();
        	}
        	
            Map<String, Object> map = new HashMap<>();
            EduRequirementInvestigation eduRequirementInvestigation = new EduRequirementInvestigation();
            eduRequirementInvestigation.setId(eduRequirementInvestigationId);
            List<EduRequirementInvestigation> eduRequirements =
                    eduRequirementInvestigationMapper.searchDetail(eduRequirementInvestigation);
            if (CollectionUtil.isNotEmpty(eduRequirements)) {
                map.put("require", eduRequirements.get(0));
                if (CollectionUtil.isNotEmpty(eduRequirements.get(0).getEduRequirementSurveyItems())) {
                	
                	
                    List<EduRequirementSurveyItem> eduRequirementSurveyItems = eduRequirements.get(0).getEduRequirementSurveyItems();
                    for (int i = 0; i < eduRequirementSurveyItems.size(); i++) {
                    	eduRequirementSurveyItems.get(i).setNum(i + 1);
                    }
                	
                    
                    map.put("its", eduRequirementSurveyItems);
                }
            } else {
                map.put("require", new EduRequirementInvestigation());
                map.put("its", new ArrayList<>());
            }
            TemplateExportParams params = new TemplateExportParams(
                    "reportTemplates/edu/eduRequireInvest.xlsx");
            params.setHeadingStartRow(0);
            params.setHeadingRows(5);

            Workbook workbook = ExcelExportUtil.exportExcel(params, map);

            PoiMergeCellUtil.mergeCells(workbook.getSheetAt(0), 3, 0, 9);
            File savefile = new File(fileTempPath);
            if (!savefile.exists()) {
                savefile.mkdirs();
            }
            String filePath = fileTempPath + "安全培训教育需求调查表-" + "-" + MyShiroUtils.getSessionUserId() + ".xlsx";
            FileOutputStream fos = new FileOutputStream(filePath);
            workbook.write(fos);
            fos.close();
            fileUtil.writeFile(response, new File(filePath));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }
    
    public Result eduRequirementInvestExcel(HttpServletResponse response, Integer reqId) {
    	Result result = new Result();
        try {        	        	
            Map<String, Object> map = new HashMap<>();
            EduRequirementInvestigation eduRequirementInvestigation = new EduRequirementInvestigation();
            eduRequirementInvestigation.setId(reqId);
            List<EduRequirementInvestigation> eduRequirements =
                    eduRequirementInvestigationMapper.searchDetail(eduRequirementInvestigation);
            if (CollectionUtil.isNotEmpty(eduRequirements)) {
                map.put("require", eduRequirements.get(0));
                if (CollectionUtil.isNotEmpty(eduRequirements.get(0).getEduRequirementSurveyItems())) {
                	
                	
                    List<EduRequirementSurveyItem> eduRequirementSurveyItems = eduRequirements.get(0).getEduRequirementSurveyItems();
                    for (int i = 0; i < eduRequirementSurveyItems.size(); i++) {
                    	eduRequirementSurveyItems.get(i).setNum(i + 1);
                    }
                	
                    
                    map.put("its", eduRequirementSurveyItems);
                }
            } else {
                map.put("require", new EduRequirementInvestigation());
                map.put("its", new ArrayList<>());
            }
            TemplateExportParams params = new TemplateExportParams(
                    "reportTemplates/edu/eduRequireInvest.xlsx");
            params.setHeadingStartRow(0);
            params.setHeadingRows(5);

            Workbook workbook = ExcelExportUtil.exportExcel(params, map);
            
            PoiMergeCellUtil.mergeCells(workbook.getSheetAt(0), 3, 0, 9);
            File savefile = new File(fileTempPath);
            if (!savefile.exists()) {
                savefile.mkdirs();
            }
            String filePath = fileTempPath + "安全培训教育需求调查表-" +"-" + MyShiroUtils.getSessionUserId() + ".xlsx";
            FileOutputStream fos = new FileOutputStream(filePath);
            workbook.write(fos);
            fos.close();
            fileUtil.writeFile(response, new File(filePath));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 安全培训教育计划表
     * @param response
     */
    public Result eduPlanExcel(HttpServletResponse response, Date year) {
        
    	Result result = new Result();
    	int eduPlanId=-1; 
    	try {

        	//根据年份找出培训计划主表ID
    		EduPlanList eduPlanListSample = new EduPlanList();
    		eduPlanListSample.setCreateYear(year);
    		eduPlanListSample.setCompanyId(MyShiroUtils.getCompanyId());

        	List<EduPlanList> eduPlanLists1 = eduPlanListMapper.search(eduPlanListSample);
        	if(CollectionUtil.isEmpty(eduPlanLists1)){
//        		result.setFalse("该年份需求调查记录为空");
        		return result;
        	}else if(eduPlanLists1.size()>1){
        		result.setFalse("该年份员工获赔记录有多个，请检查");
        		return result;
        	}else{
        		eduPlanId = eduPlanLists1.get(0).getId();
        	}
            Map<String, Object> map = new HashMap<>();
            EduPlanList eduPlanList = new EduPlanList();
            eduPlanList.setId(eduPlanId);
//            eduPlanList.setCreateYear(DateUtil.parse(year + "0101"));
            List<EduPlanList> eduPlanLists = eduPlanListMapper.searchDetail(eduPlanList);
            if (CollectionUtil.isEmpty(eduPlanLists)) {
                return result;
            }
            map.put("plan", eduPlanLists.get(0));
            if (CollectionUtil.isEmpty(eduPlanLists.get(0).getEduPlanItems())) {
                map.put("items", new ArrayList<>());
            } else {
                List<EduPlanItem> eduPlanItems = eduPlanLists.get(0).getEduPlanItems();
                for (int i = 0; i < eduPlanItems.size(); i++) {
                    eduPlanItems.get(i).setNum(i + 1);
                }
                map.put("items", eduPlanItems);
            }
            map.put("title", "（2017）培训教育活动计划表");
            TemplateExportParams params = new TemplateExportParams(
                    "reportTemplates/edu/eduSafePlan.xlsx");
            params.setHeadingStartRow(0);
            params.setHeadingRows(5);

            Workbook workbook = ExcelExportUtil.exportExcel(params, map);

            PoiMergeCellUtil.mergeCells(workbook.getSheetAt(0), 5, 0, 7);
            File savefile = new File(fileTempPath);
            if (!savefile.exists()) {
                savefile.mkdirs();
            }
            String filePath = fileTempPath + "培训教育活动计划表-" + "-" + MyShiroUtils.getSessionUserId() + ".xlsx";
//            String filePath = fileTempPath + "从业人员花名册-" + "-" + ".xlsx";
            FileOutputStream fos = new FileOutputStream(filePath);
            workbook.write(fos);
            fos.close();
            fileUtil.writeFile(response, new File(filePath));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;

    }

    /**
     * 安全生产相关负责人及安全生产管理人员安全培训教育登记表
     *done
     * @param response
     */
    public Result eduCertificateExcel(HttpServletResponse response,Date year) {
    	Result result = new Result();

    	try {
        	
        	Calendar   calendar   =   new   GregorianCalendar(); 
        	calendar.setTime(year);
        	calendar.add(calendar.YEAR, 1);
        	
        	
            EduCertificate eduCertificateT = new EduCertificate();
            
            //设定起始查询时间，查询该年全年记录
            eduCertificateT.setStartDate(year);
            eduCertificateT.setEndDate(calendar.getTime());
            eduCertificateT.setCompanyId(MyShiroUtils.getCompanyId());

//			System.out.println("结束时间"+calendar.getTime());

            Map<String, Object> map = new HashMap<>();

            List<EduCertificate> eduCertificates = eduCertificateMapper.searchDetail(eduCertificateT);
            if (CollectionUtil.isEmpty(eduCertificates)) {
            	return result;
            }
            int i=1;
            for(EduCertificate eduCert:eduCertificates){
            	eduCertificates.get(i-1).setNum(i);
            	i++;
            }
            map.put("eduCts", eduCertificates);
            TemplateExportParams params = new TemplateExportParams(
                    "reportTemplates/edu/eduCertificate.xlsx");
            params.setHeadingStartRow(0);
            params.setHeadingRows(3);

            Workbook workbook = ExcelExportUtil.exportExcel(params, map);

            PoiMergeCellUtil.mergeCells(workbook.getSheetAt(0), 3, 0, 12);
            File savefile = new File(fileTempPath);
            if (!savefile.exists()) {
                savefile.mkdirs();
            }
            String filePath = fileTempPath + "安全生产相关负责人及安全生产管理人员安全培训教育登记表-" + "-" + MyShiroUtils.getSessionUserId() + ".xlsx";
            FileOutputStream fos = new FileOutputStream(filePath);
            workbook.write(fos);
            fos.close();
            fileUtil.writeFile(response, new File(filePath));
        } catch (IOException e) {
            e.printStackTrace();
        }
    	return result;
    }

    /**
     * 新入职人员安全培训教育登记表
     *
     * @param response
     */
    public void eduTrainExcel(HttpServletResponse response,Date year) {
    	Result result = new Result();

    	try {
        	Calendar   calendar   =   new   GregorianCalendar(); 
        	calendar.setTime(year);
        	calendar.add(calendar.YEAR, 1);
    		
        	EduEntryTraining eduEntryTrainingT =new EduEntryTraining() ;
        	eduEntryTrainingT.setStartDate(year);
        	eduEntryTrainingT.setEndDate(calendar.getTime());
//        	eduEntryTrainingT.setCompanyId(MyShiroUtils.getCompanyId());

            List<EduEntryTraining> eduEntryTrainings = eduEntryTrainingMapper.searchDetail(eduEntryTrainingT);
            if (CollectionUtil.isEmpty(eduEntryTrainings)) {
                return;
            }
            for (int i = 0; i < eduEntryTrainings.size(); i++) {
                eduEntryTrainings.get(i).setNum(i + 1);
            }
            Map<String, Object> map = new HashMap<>();
            map.put("eduET", eduEntryTrainings);
            TemplateExportParams params = new TemplateExportParams(
                    "reportTemplates/edu/eduEntryTrain.xlsx");
            params.setHeadingStartRow(0);
            params.setHeadingRows(3);

            Workbook workbook = ExcelExportUtil.exportExcel(params, map);

            PoiMergeCellUtil.mergeCells(workbook.getSheetAt(0), 3, 0, 13);
            File savefile = new File(fileTempPath);
            if (!savefile.exists()) {
                savefile.mkdirs();
            }
            String filePath = fileTempPath + "新入职人员安全培训教育登记表-" + "-" + MyShiroUtils.getSessionUserId() + ".xlsx";
            FileOutputStream fos = new FileOutputStream(filePath);
            workbook.write(fos);
            fos.close();
            fileUtil.writeFile(response, new File(filePath));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 转岗、调岗、脱岗人员安全培训教育登记表
     *done
     * @param response
     */
    public Result eduReassignmentExcel(HttpServletResponse response,Date year) {
    	Result result = new Result();

    	try {
        	Calendar   calendar   =   new   GregorianCalendar(); 
        	calendar.setTime(year);
        	calendar.add(calendar.YEAR, 1);
        	
            EduReassignment eduReassignmentT = new EduReassignment();
            
            //设定起始查询时间，查询该年全年记录
            eduReassignmentT.setStartDate(year);
            eduReassignmentT.setEndDate(calendar.getTime());
            eduReassignmentT.setCompanyId(MyShiroUtils.getCompanyId());
        	
            List<EduReassignment> eduReassignments = eduReassignmentMapper.searchDetail(eduReassignmentT);
            if (CollectionUtil.isEmpty(eduReassignments)) {
                return result;
            }
            for (int i = 0; i < eduReassignments.size(); i++) {
                eduReassignments.get(i).setNum(i + 1);
            }
            Map<String, Object> map = new HashMap<>();
            map.put("eduR", eduReassignments);
            TemplateExportParams params = new TemplateExportParams(
                    "reportTemplates/edu/eduReassignment.xlsx");
            params.setHeadingStartRow(0);
            params.setHeadingRows(3);

            Workbook workbook = ExcelExportUtil.exportExcel(params, map);

            PoiMergeCellUtil.mergeCells(workbook.getSheetAt(0), 3, 0, 13);
            File savefile = new File(fileTempPath);
            if (!savefile.exists()) {
                savefile.mkdirs();
            }
            String filePath = fileTempPath + "转岗、调岗、脱岗人员安全培训教育登记表-" + "-" + MyShiroUtils.getSessionUserId() + ".xlsx";
            FileOutputStream fos = new FileOutputStream(filePath);
            workbook.write(fos);
            fos.close();
            fileUtil.writeFile(response, new File(filePath));
        } catch (IOException e) {
            e.printStackTrace();
        }
    	return result;
    }

    /**
     * 从业人员日常安全培训教育登记表
     *done
     * @param response
     */
    public Result eduDailyInfoExcel(HttpServletResponse response, String year) {
    	Result result = new Result();

    	try {
    		     	
            Date startDate = DateUtil.parse(year + "0101");
            Date endDate = DateUtil.parse(year + "1231");
            EduDailyInfo eduDailyInfo = new EduDailyInfo();
            eduDailyInfo.setEndDate(endDate);
            eduDailyInfo.setStartDate(startDate);
            eduDailyInfo.setCompanyId(MyShiroUtils.getCompanyId());

            List<EduDailyInfo> eduDailyInfos = eduDailyInfoMapper.searchDetail(eduDailyInfo);
            if (CollectionUtil.isEmpty(eduDailyInfos)) {
                return result;
            }
            for (int i = 0; i < eduDailyInfos.size(); i++) {
                eduDailyInfos.get(i).setNum(i + 1);
            }
            Map<String, Object> map = new HashMap<>();
            map.put("eduD", eduDailyInfos);
            TemplateExportParams params = new TemplateExportParams(
                    "reportTemplates/edu/eduDailyInfo.xlsx");
            params.setHeadingStartRow(0);
            params.setHeadingRows(3);

            Workbook workbook = ExcelExportUtil.exportExcel(params, map);

            PoiMergeCellUtil.mergeCells(workbook.getSheetAt(0), 3, 0, 13);
            File savefile = new File(fileTempPath);
            if (!savefile.exists()) {
                savefile.mkdirs();
            }
            String filePath = fileTempPath + "从业人员日常安全培训教育登记表" + "-" + MyShiroUtils.getSessionUserId() + ".xlsx";
            FileOutputStream fos = new FileOutputStream(filePath);
            workbook.write(fos);
            fos.close();
            fileUtil.writeFile(response, new File(filePath));
        } catch (IOException e) {
            e.printStackTrace();
        }
    	return result;
    }

    /**
     * 教育培训活动记录excel导出
     *
     * @param response
     * @param eduDailyRecordId
     */
    public void eduDailyRecordExcel(HttpServletResponse response, int eduDailyRecordId) {
        try {
            EduDailyRecord eduDailyRecord = eduDailyRecordMapper.selectByPrimaryKey(eduDailyRecordId);
            if (ObjectUtil.isNull(eduDailyRecord)) {
                return;
            }
            Map<String, Object> map = new HashMap<>();
            map.put("edt", eduDailyRecord);
            TemplateExportParams params = new TemplateExportParams(
                    "reportTemplates/edu/eduDailyRecord.xlsx");
            params.setHeadingStartRow(0);
            params.setHeadingRows(3);

            Workbook workbook = ExcelExportUtil.exportExcel(params, map);

            PoiMergeCellUtil.mergeCells(workbook.getSheetAt(0), 3, 0, 13);
            File savefile = new File(fileTempPath);
            if (!savefile.exists()) {
                savefile.mkdirs();
            }
            String filePath = fileTempPath + "教育培训活动记录" + "-" + MyShiroUtils.getSessionUserId() + ".xlsx";
            FileOutputStream fos = new FileOutputStream(filePath);
            workbook.write(fos);
            fos.close();
            fileUtil.writeFile(response, new File(filePath));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void eduDailyExamineListExcel(HttpServletResponse response, int eduDailyExamineListId) {
        try {
            EduDailyExamineList eduDailyExamineList =
                    eduDailyExamineListMapper.selectByPrimaryKey(eduDailyExamineListId);
            EduDailyExamineScore eduDailyExamineScore = new EduDailyExamineScore();
            eduDailyExamineScore.setExamineId(eduDailyExamineListId);
            List<EduDailyExamineScore> eduDailyExamineScores =
                    eduDailyExamineScoreMapper.searchDetail(eduDailyExamineScore);
            for (int i = 0; i < eduDailyExamineScores.size(); i++) {
                eduDailyExamineScores.get(i).setNum(i + 1);
            }
            List<EduDailyExamineScoreBean> eduDailyExamineScoreBeans=new ArrayList<>();
            for (int i = 0; i < eduDailyExamineScores.size(); i++) {
                    if((i+1)<eduDailyExamineScores.size()){
                        eduDailyExamineScoreBeans.add(new EduDailyExamineScoreBean(eduDailyExamineScores.get(i)
                                ,eduDailyExamineScores.get(i+1)));
                        i++;
                    }else{
                        eduDailyExamineScoreBeans.add(new EduDailyExamineScoreBean(eduDailyExamineScores.get(i)));
                    }
            }
            Map<String, Object> map = new HashMap<>();
            map.put("edel", eduDailyExamineList);
            map.put("edes", eduDailyExamineScoreBeans);
            TemplateExportParams params = new TemplateExportParams(
                    "reportTemplates/edu/eduDailyExamine.xlsx");
            params.setHeadingStartRow(0);
            params.setHeadingRows(3);

            Workbook workbook = ExcelExportUtil.exportExcel(params, map);

            PoiMergeCellUtil.mergeCells(workbook.getSheetAt(0), 3, 0, 13);
            File savefile = new File(fileTempPath);
            if (!savefile.exists()) {
                savefile.mkdirs();
            }
            String filePath = fileTempPath + "安全教育培训考核表" + "-" + MyShiroUtils.getSessionUserId() + ".xlsx";
            FileOutputStream fos = new FileOutputStream(filePath);
            workbook.write(fos);
            fos.close();
            fileUtil.writeFile(response, new File(filePath));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
